package com.tycoin.app.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import javax.crypto.Cipher;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Validator;

import com.tycoin.app.response.BaseRespose;
import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;

 import com.tycoin.common.bean.PageInfo;
import com.tycoin.common.jpa.PropertyFilter;
import com.tycoin.common.jpa.SpecificationUtils;
import com.tycoin.common.repository.AbstractRepository;
import com.tycoin.utils.HttpRequestUtils;
import com.tycoin.utils.UnicodeUtils;
import com.util.HttpClientUtils;
import com.util.IpUtils;

import net.sf.json.JSONObject;

 
public abstract class AbstractController {
    protected static final String SEARCH_KEY = "search_";

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 验证Bean实例对象
     */
     protected Validator validator;

    
    /**
     * 获取IP地址
     *
     * @param request
     * @return
     */
    protected String getIpAddr(HttpServletRequest request) {
        return IpUtils.getIpAddr(request);
    }

    protected String getRequestUrl(HttpServletRequest request) {
        StringBuffer sb = request.getRequestURL();
        String queryString = request.getQueryString();
        if (StringUtils.isNotEmpty(queryString)) {
            sb.append("?").append(queryString);
        }
        return sb.toString();
    }

    protected String getAllParam(HttpServletRequest request) {
        List<String> nameList = new ArrayList<String>();
        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            nameList.add(name);
        }

        // Collections.sort(nameList, new Comparator<String>() {
        // public int compare(String o1, String o2) {
        // return o1.compareTo(o2);
        // }
        // });

        StringBuffer info = new StringBuffer("params:");
        for (String name : nameList) {
            String value = request.getParameter(name);
            info.append("<").append(name).append("=");
            info.append(value).append(">");
            if (names.hasMoreElements()) {
                info.append(",");
            }
        }
        return info.toString();
    }
    
    
	public String  isNotparam(Map<String,String> map){
		String result="";
 		for (Map.Entry<String, String> entry : map.entrySet()) {  
  		     if(!StringUtils.isNotBlank(entry.getValue())){
	             result="{\"result_code\":\"201\",\"return_"
	             		+ "msg\":\""+entry.getKey()+"参数不能为空\"}";
	        }
		}  
 		return result;
		
	}
	
	public Map<String,Object>  isNotparamReturnMap(Map<String,String> map){
		Map<String, Object> mapCode=new HashMap<>();
 		for (Map.Entry<String, String> entry : map.entrySet()) {  
  		     if(!StringUtils.isNotBlank(entry.getValue())){
  		    	mapCode.put("code", 201);
  		    	mapCode.put("msg", entry.getKey()+"参数不能为空");	             
	        }
		}  
		return mapCode;
		
		
		
  	}
	
	/**
	 * 从request中获得参数Map，并返回可读的Map
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static Map<String,String> getAllRequestParam(HttpServletRequest request) {
		// 参数Map
		Map properties = request.getParameterMap();
		// 返回值Map
		Map returnMap = new HashMap();
		Iterator entries = properties.entrySet().iterator();
		Map.Entry entry;
		String name = "";
		String value = "";
		while (entries.hasNext()) {
			entry = (Map.Entry) entries.next();
			name = (String) entry.getKey();
			Object valueObj = entry.getValue();
			if(null == valueObj){
				value = "";
			}else if(valueObj instanceof String[]){
				String[] values = (String[])valueObj;
				for(int i=0;i<values.length;i++){
					value = values[i] + ",";
				}
				value = value.substring(0, value.length()-1);
			}else{
				value = valueObj.toString();
			}
			returnMap.put(name, value);
		}
		return returnMap;
	}
	
	/**
	 * 验证请求参数不为空  返回
	 * @param map
	 * @return
	 */
	public Map<String,String>  verifyRequestParameters(HttpServletRequest request){
		Map<String,String> map=getAllRequestParam(request);
		Map<String, String> mapCode=new HashMap<>();
 		for (String key : map.keySet()) {  
  		     if(StringUtils.isNotBlank(key)){
  		    	mapCode.put(key, map.get(key));  		    		             
	        }
		}  
		return mapCode;		
  	}
 
	 /**
     * 根据请求获取查询结果
     *
     * @param request
     * @param pageInfo
     * @param abstractRepository
     * @return
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    protected <T> Page<T> find(final HttpServletRequest request, final PageInfo pageInfo, final AbstractRepository abstractRepository) {
        Specification<T> specification = getSpecification(request);
        PageRequest pageRequest = PageInfo.getPageRequest(pageInfo);
        Page<T> page = abstractRepository.findAll(specification, pageRequest);
        return page;
    }
    /**
     * 根据请求获取查询对象
     *
     * @param request
     * 
     * @param <T>
     * @return
     */
    protected static <T> Specification<T> getSpecification(final HttpServletRequest request) {
        List<PropertyFilter> pfList = getPropertyFilters(request);
        return SpecificationUtils.getSpecification(pfList);
    }

    /**
     * 根据请求获取查询对象
     *
     * @param request
     * @param <T>
     * @return
     */
    protected static <T> List<PropertyFilter> getPropertyFilters(final HttpServletRequest request) {
        Map<String, String> searchMap = getParametersStartingWith(request);
        return getPropertyFilters(searchMap);
    }
    

    /**
     * 根据过滤条件获取查询对象
     *
     * @param map
     * @param <T>
     * @return
     */
    protected static <T> List<PropertyFilter> getPropertyFilters(final Map<String, String> map) {
        List<PropertyFilter> pfList = new ArrayList<PropertyFilter>();
        for (String key : map.keySet()) {
            if (StringUtils.isNotEmpty(map.get(key))) {
                pfList.add(new PropertyFilter(key, map.get(key)));
            }
        }
        return pfList;
    }
    /**
     * 根据请求获取过滤条件
     *
     * @param request
     * @return
     */
    protected static Map<String, String> getParametersStartingWith(final HttpServletRequest request) {
        return getParametersStartingWith(request, SEARCH_KEY);
    }

    /**
     * 取得带相同前缀的Request Parameters.
     * <p/>
     * 返回的结果Parameter名已去除前缀.
     */
    protected static Map<String, String> getParametersStartingWith(final HttpServletRequest request, final String prefix) {
        String prefixStr = StringUtils.trimToEmpty(prefix);
        Map<String, String> params = new TreeMap<String, String>();

        Enumeration<String> paramNames = request.getParameterNames();
        while (paramNames != null && paramNames.hasMoreElements()) {
            String paramName = (String) paramNames.nextElement();
            if (StringUtils.isEmpty(prefixStr) || paramName.startsWith(prefixStr)) {
                String unprefixed = paramName.substring(prefixStr.length());
                String[] values = request.getParameterValues(paramName);
                if (values == null || values.length == 0) {
                    // Do nothing, no values found at all.
                } else {
                    params.put(unprefixed, values[0]);
                }
            }
        }
        return params;
    }

    
    public static String getRandomString(int length) { //length表示生成字符串的长度  
        String base = "abcdefghijklmnopqrstuvwxyz";     
        Random random = new Random();     
        StringBuffer sb = new StringBuffer();     
        for (int i = 0; i < length; i++) {     
            int number = random.nextInt(base.length());     
            sb.append(base.charAt(number));     
        }     
        return sb.toString();     
     }     
    
    
    public static String findIpToAddress(String ip){
    	
    	String result="";
 	HttpClientUtils hd = new HttpClientUtils();  
    if("0:0:0:0:0:0:0:1".equals(ip)||"127.0.0.1".equals(ip)){
  	  ip="101.230.199.150";
    }
  //    String result= hd.get("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip="+ip);  
      JSONObject json=HttpRequestUtils.httpGet("http://ip.taobao.com/service/getIpInfo.php?ip="+ip);

 //    JSONObject jsStr = JSONObject.fromObject(result); 
     String code= json.getString("code");
     // {"ret":1,"start":-1,"end":-1,"country":"\u4e2d\u56fd","province":"\u4e0a\u6d77","city":"\u4e0a\u6d77","district":"","isp":"","type":"","desc":""}
   //  "province": "广东",  
    // "city": "广州",  
 
     if("0".equals(code)){
         JSONObject data= JSONObject.fromObject( json.get("data")); 
          if(data.getString("region").equals(data.getString("city"))){
          	 result=data.getString("country")+data.getString("region")+data.getString("isp");
         }else{
         	 result=data.getString("country")+data.getString("region")+data.getString("city")+data.getString("isp");
           }
      }
 
    return result;
    	
    }
    
    
    
    
    public static String unicodetoUTF(String unicodeStr) { 
    	 
    	String gbkStr = null;
		try {
			gbkStr = new String(unicodeStr.getBytes("ISO8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
 			 
		} 
    	return gbkStr; 
     
}
    
    
    
    
    
 // 创建目录
 	public static boolean createDir(String destDirName) {
 		File dir = new File(destDirName);
 		if (dir.exists()) {// 判断目录是否存在
 			System.out.println("创建目录失败，目标目录已存在！");
 			return false;
 		}
 		if (!destDirName.endsWith(File.separator)) {// 结尾是否以"/"结束
 			destDirName = destDirName + File.separator;
 		}
 		if (dir.mkdirs()) {// 创建目标目录
 			System.out.println("创建目录成功！" + destDirName);
 			return true;
 		} else {
 			System.out.println("创建目录失败！");
 			return false;
 		}
 	}
    
	 
    
}
